package com.yt.service.impl;

import com.yt.entity.Author;
import com.yt.entity.CommonResult;
import com.yt.entity.Novel;
import com.yt.loadbalance.MyLoadBalance;
import com.yt.mapper.AuthorMapper;
import com.yt.service.AuthorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class AuthorServiceImpl implements AuthorService {
    @Resource
    AuthorMapper authorMapper;
    @Resource
    RestTemplate restTemplate;
    @Resource
    MyLoadBalance myLoadBalance;

    @Resource
    private DiscoveryClient discoveryClient;
    public static final String url="http://RIBBON-PROVIDER";

    @Override
    public Author getAuthorById(Integer id) {
        return authorMapper.getAuthorById(id);
    }

    @Override

    public List<Novel> getNovelsByAid(Integer aid) {

        List<ServiceInstance>  serviceInstanceList=discoveryClient.getInstances("RIBBON-PROVIDER");
        if(serviceInstanceList== null || serviceInstanceList.size() <= 0){
            log.info("没有 provider 服务应用");
        }else{
            log.info("发现服务："+serviceInstanceList.size());
        }

        ServiceInstance serviceInstance= myLoadBalance.instance(serviceInstanceList);

        String uri=serviceInstance.getUri().toString();
        log.info("uri------->>>>"+serviceInstance.getUri().toString());
        CommonResult<List<Novel>> result=  restTemplate.getForObject(uri+"/novel/"+aid,CommonResult.class);

        return result.getT();
    }



}
